package com.beimihu.leetcode;

import java.util.ArrayList;
import java.util.List;

//https://leetcode.cn/problems/zigzag-conversion/solutions/21610/zzi-xing-bian-huan-by-jyd/?envType=study-plan-v2&envId=top-interview-150
public class NWord6 {
    public static String convert(String s, int numRows) {
        if(numRows < 2 ) return s;

        List<StringBuilder> rows = new ArrayList<>();
        for(int i = 0 ; i < numRows ; i++){
            rows.add(new StringBuilder());
        }
        int i = 0 ;
        int flag = -1;
        for(char c : s.toCharArray()){
            rows.get(i).append(c);
            if(i == 0 || i == numRows - 1){
                flag = -flag;
            }
            i = i + flag;
        }

        StringBuilder res = new StringBuilder();
        for(StringBuilder row : rows){
            res.append(row);
        }
        return res.toString();
    }

    public String convertV2(String s, int numRows) {
        if (s.length() <= 2 || numRows <= 1) {
            return s;
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numRows; i++) {
            if (i == 0 || i == numRows - 1) {
                if (i < s.length()) {
                    int p1 = i;
                    while (p1 < s.length()) {
                        sb.append(s.charAt(p1));
                        p1 += 2 * numRows - 2;
                    }
                }
            }
            else {
                int p1 = i;
                int p2 = i + 2 * (numRows - i - 1);

                while (p1 < s.length() && p2 < s.length()) {
                    sb.append(s.charAt(p1));
                    sb.append(s.charAt(p2));

                    p1 += 2 * numRows - 2;
                    p2 += 2 * numRows - 2;
                }

                if (p1 < s.length()) {
                    sb.append(s.charAt(p1));
                }
            }
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        String s = "PAYPALISHIRING";
        String res = convert(s,3);
        System.out.println(res);
    }

}
